import { Ref, ref } from "vue";
import Sort from "@/models/Sort";

export default function TableSort(tableData: Ref) {
  const defaultSort = { prop: "id", order: "ascending" };
  const sortKey = ref("id");
  const sortChange = (sort: Sort) => {
    sortKey.value = sort.prop;
    const notNullData = [];
    const nullData = [];
    for (let i = 0; i < tableData.value.length; i++) {
      let temp = null;
      temp = tableData.value[i][sortKey.value];
      if (temp === null || undefined === temp) {
        nullData.push(tableData.value[i]);
      } else {
        notNullData.push(tableData.value[i]);
      }
    }
    switch (sort.order) {
      case null:
        break;
      case "ascending":
        notNullData.sort(sortAsc);
        break;
      case "descending":
        notNullData.sort(sortDesc);
        break;
    }
    tableData.value = notNullData.concat(nullData);
  };

  const sortAsc = (a: Record<string, unknown>, b: Record<string, unknown>) => {
    a[sortKey.value] = a[sortKey.value] === "" ? "" : a[sortKey.value];
    b[sortKey.value] = b[sortKey.value] === "" ? "" : b[sortKey.value];
    if (typeof b[sortKey.value] === "number") {
      const c = a as Record<string, number>;
      const d = b as Record<string, number>;
      return d[sortKey.value] - c[sortKey.value];
    } else {
      const c = a as Record<string, string>;
      const d = b as Record<string, string>;
      return d[sortKey.value].localeCompare(c[sortKey.value]);
    }
  };
  const sortDesc = (a: Record<string, unknown>, b: Record<string, unknown>) => {
    a[sortKey.value] = a[sortKey.value] === "" ? "" : a[sortKey.value];
    b[sortKey.value] = b[sortKey.value] === "" ? "" : b[sortKey.value];
    if (typeof b[sortKey.value] === "number") {
      const c = a as Record<string, number>;
      const d = b as Record<string, number>;
      return c[sortKey.value] - d[sortKey.value];
    } else {
      const c = a as Record<string, string>;
      const d = b as Record<string, string>;
      return c[sortKey.value].localeCompare(d[sortKey.value]);
    }
  };
  return {
    defaultSort,
    sortChange,
  };
}
